package dao

import (
	"fmt"
	__ "user-srv/basic/proto"
	"user-srv/handler/models"
)

// 信任设备添加
func TrustedDeviceAdd(in *__.TrustedDeviceAddReq) (*models.TrustedDevice, error) {
	var trustedDevice models.TrustedDevice
	exists, err := trustedDevice.CheckDeviceExists(uint64(in.UserId), in.DeviceName)
	if err != nil {
		return nil, fmt.Errorf("查询设备失败")
	}
	if exists {
		return nil, fmt.Errorf("设备已存在")
	}

	trustedDevice.UserId = uint64(in.UserId)
	trustedDevice.DeviceName = in.DeviceName
	trustedDevice.DeviceType = in.DeviceType
	trustedDevice.OsType = in.OsType
	trustedDevice.IsTrusted = 1 // 设置默认值
	err = trustedDevice.TrustedDeviceAdd()
	if err != nil {
		return nil, fmt.Errorf("添加设备失败: %v", err)
	}

	return &trustedDevice, nil
}

// 信任设备删除
func TrustedDeviceDel(in *__.TrustedDeviceDelReq) (*models.TrustedDevice, error) {
	var trustedDevice models.TrustedDevice
	trustedDevice.UserId = uint64(in.UserId)
	trustedDevice.Id = uint64(in.Id)
	err := trustedDevice.TrustedDeviceDel()
	if err != nil {
		return nil, fmt.Errorf("删除设备失败")
	}

	return &trustedDevice, nil
}

// 信任设备修改
func TrustedDeviceUpdate(in *__.TrustedDeviceUpdateReq) (*models.TrustedDevice, error) {
	var trustedDevice models.TrustedDevice
	trustedDevice.UserId = uint64(in.UserId)
	trustedDevice.Id = uint64(in.Id)
	trustedDevice.DeviceName = in.DeviceName
	trustedDevice.DeviceType = in.DeviceType
	trustedDevice.OsType = in.OsType
	err := trustedDevice.TrustedDeviceUpdate()
	if err != nil {
		return nil, fmt.Errorf("修改设备失败")
	}

	return &trustedDevice, nil
}

// 信任设备展示
func TrustedDeviceFind(in *__.TrustedDeviceFindReq) ([]*__.TrustedDeviceFind, error) {
	var trustedDevice models.TrustedDevice
	var trustedDeviceFind []*__.TrustedDeviceFind
	trustedDevice.UserId = uint64(in.UserId)

	find, err := trustedDevice.TrustedDeviceFind()
	if err != nil {
		return nil, fmt.Errorf("查询设备失败")
	}
	for _, device := range find {
		trustedDeviceFind = append(trustedDeviceFind, &__.TrustedDeviceFind{
			Id:         int64(device.Id),
			DeviceName: device.DeviceName,
			DeviceType: device.DeviceType,
			OsType:     device.OsType,
		})
	}

	return trustedDeviceFind, nil
}
